class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        l, r, t, b = 0, n-1, 0, n-1
        ans = [ [0]* n for _ in range(n)]
        num = 1

        while l < r and t < b:

            # 从左到右填充
            for i in range(l, r):
                ans[t][i] = num
                num += 1

            # 从上到下填充
            for i in range(t, b):
                ans[i][r] = num
                num += 1

            # 从右到左填充
            for i in range(r, l, -1):
                ans[b][i] = num
                num += 1

            # 从下到上填充
            for i in range(b, t, -1):
                ans[i][l] = num
                num += 1

            l += 1
            r -= 1
            t += 1
            b -= 1
        
        if n%2 == 1:
            ans[n//2][n//2] = n*n

        return ans

            